package com.hust.chatvedio.fragment;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.view.menu.MenuBuilder;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.hust.chatvedio.MainActivity;
import com.hust.chatvedio.MenuActivity;
import com.hust.chatvedio.R;
import com.hust.chatvedio.adapter.CityAdapter;
import com.hust.chatvedio.AddFriendActivity;
import com.hust.chatvedio.model.CityBean;
import com.mcxtzhang.indexlib.IndexBar.widget.IndexBar;
import com.mcxtzhang.indexlib.suspension.SuspensionDecoration;
import org.json.JSONArray;
import org.json.JSONException;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



public class ContactFragment extends Fragment {

    private Toolbar mToolbar;
    private static final String TAG = "zxt";
    private static final String INDEX_STRING_TOP = "↑";
    private ProgressDialog progressDialog;
    //发送信息地址
    private static String url_getChatList = MainActivity.BaseURL + "getChatList";
    private RecyclerView mRv;
    private CityAdapter mAdapter;
    private LinearLayoutManager mManager;
    private List<CityBean> mDatas = new ArrayList<>();
    private SuspensionDecoration mDecoration;
    private int success;//服务器返回值
    private String friend_name;//服务器返回值
    private String friend_avatar;//服务器返回值
    /**
     * 右侧边栏导航区域
     */
    private IndexBar mIndexBar;

    /**
     * 显示指示器DialogText
     */
    private TextView mTvSideBarHint;
    private Canvas canvas;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_contact, container, false);
        initView(view);
        setHasOptionsMenu(true);
        return view;
    }

    private void initView(View view) {
        mRv = (RecyclerView) view.findViewById(R.id.rv);
        mRv.setLayoutManager(mManager = new LinearLayoutManager(getActivity()));
        mAdapter = new CityAdapter(getActivity(), mDatas);
        mRv.setAdapter(mAdapter);
        mRv.addItemDecoration(mDecoration = new SuspensionDecoration(getActivity(), mDatas));
        //如果add两个，那么按照先后顺序，依次渲染。
        // mRv.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST,canvas,mRv));

        //使用indexBar
        mTvSideBarHint = (TextView)view.findViewById(R.id.tvSideBarHint);//HintTextView
        mIndexBar = (IndexBar) view.findViewById(R.id.indexBar);//IndexBar

        //indexbar初始化
        mIndexBar.setmPressedShowTextView(mTvSideBarHint)//设置HintTextView
                .setNeedRealIndex(true)//设置需要真实的索引
                .setmLayoutManager(mManager);//设置RecyclerView的LayoutManager
        mToolbar = (Toolbar) view.findViewById(R.id.toolbar);
        mToolbar.setOverflowIcon(getResources().getDrawable(R.drawable.add));
        MenuActivity menuActivity = (MenuActivity) getActivity();
        menuActivity.setSupportActionBar(mToolbar);
        mToolbar.setTitle("通讯录");
    }

    private void initDatas() {
        RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
        Map<String, String> map = new HashMap<>();
        map.put("userName", MainActivity.userName);
        //在进行异步任务前先显示一个 Progress Dialog
        progressDialog=new ProgressDialog(getActivity());
        progressDialog.setMessage("获取通讯录列表");
        progressDialog.setIndeterminate(false);
        progressDialog.setCancelable(true);
        progressDialog.show();
        mDatas = new ArrayList<>();
        Request request = new JsonObjectRequest(1, url_getChatList, new Gson().toJson(map),
                jsonObject -> {
                    try {
                        success = jsonObject.getInt("success");
                        if (success == 1) {
                            mDatas.clear();
                            //ChatVedio的头部 也是可以右侧IndexBar导航索引的，
                            // 但是它不需要被ItemDecoration设一个标题titile
                            mDatas.add((CityBean) new CityBean("新的朋友",R.drawable.addpeople).setTop(true).setBaseIndexTag(INDEX_STRING_TOP));
                            mDatas.add((CityBean) new CityBean("群聊",R.drawable.groupchat).setTop(true).setBaseIndexTag(INDEX_STRING_TOP));
                            mDatas.add((CityBean) new CityBean("标签",R.drawable.lable).setTop(true).setBaseIndexTag(INDEX_STRING_TOP));
                            mDatas.add((CityBean) new CityBean("公众号",R.drawable.publicnews).setTop(true).setBaseIndexTag(INDEX_STRING_TOP));
                            progressDialog.dismiss();
                            JSONArray data = jsonObject.getJSONArray("data");
                            for(int i=0;i<data.length();i++) {
                                CityBean cityBean = new CityBean();
                                cityBean.setCity(data.getJSONObject(i).optString("name"));//设置城市名称
                                cityBean.setAvatarUrl(data.getJSONObject(i).optString("avatar"));//设置头像
                                mDatas.add(cityBean);
                            }
                            mAdapter.setDatas(mDatas);
                            mAdapter.notifyDataSetChanged();
                            mIndexBar.setmSourceDatas(mDatas)//设置数据
                                    .invalidate();
                            mDecoration.setmDatas(mDatas);
                        } else if (success == 0) {
                            progressDialog.dismiss();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }, volleyError -> {
                });
        requestQueue.add(request);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.main, menu);
        if (menu != null) {
            if (menu.getClass() == MenuBuilder.class) {
                try {
                    Method m = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
                    m.setAccessible(true);
                    m.invoke(menu, true);
                } catch (Exception e) {
                }
            }
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.search_item:
                Toast.makeText(getContext(), "开发中，耐心等待哦~", Toast.LENGTH_SHORT).show();
                break;
            case R.id.chat_item:
                Toast.makeText(getContext(), "开发中，耐心等待哦~", Toast.LENGTH_SHORT).show();
                break;
            case R.id.addfriend_item:
                Intent intent = new Intent(getActivity(), AddFriendActivity.class);
                startActivity(intent);
                break;
            case R.id.addGroup_item:
                Toast.makeText(getContext(), "开发中，耐心等待哦~", Toast.LENGTH_SHORT).show();
                break;
            case R.id.pay_item:
                Toast.makeText(getContext(), "开发中，耐心等待哦~", Toast.LENGTH_SHORT).show();
                break;
            case R.id.help_item:
                Toast.makeText(getContext(), "开发中，耐心等待哦~", Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onResume() {
        super.onResume();
        initDatas();
    }
}